﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Configuration;
using System.Net.Mail;
using System.Net.Mime;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Configuration;


public class MailSender
	{
		public static bool SendEmail(string emailTo, string htmlReport, byte[] pdfReportBytes)
		{
			var msg = new MailMessage();
			msg.To.Add(new MailAddress(emailTo));
			msg.IsBodyHtml = true;
			msg.Body = htmlReport;
			msg.Subject = "PA - Weekly Progress Report";

			bool sendStatus = false;

			using (Stream ms = new MemoryStream(pdfReportBytes))
			{
				msg.Attachments.Add(new Attachment(ms, "WeeklyProgressReport.pdf", MediaTypeNames.Application.Pdf));

				try
				{
					Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);
					MailSettingsSectionGroup mailSettings = (MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

					msg.From = new MailAddress(mailSettings.Smtp.From);
					SmtpClient mailUserClient = new SmtpClient();
					mailUserClient.EnableSsl = Convert.ToBoolean(WebConfigurationManager.AppSettings["NotificationEmailEnableSSL"]);
					mailUserClient.Send(msg);

					sendStatus = true;
				}
				catch (Exception ex)
				{
					PALogManager.ExceptionLog(ex);
				}
			}

			return sendStatus;

		}


		public static EmailValidationStatus IsRealEmail(string inputEmail)
		{
			if (string.IsNullOrEmpty(inputEmail))
				return EmailValidationStatus.IncorectFormat;

			string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
				  @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
				  @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";
			Regex re = new Regex(strRegex);
			
			if (!re.IsMatch(inputEmail))
				return EmailValidationStatus.IncorectFormat;


			int port;

			string[] host = (inputEmail.Split('@'));
			string hostname = host[1];

			switch(hostname)
			{
				case "gmail.com":
					port = 587;
					break;
				case "yahoo.com":
					port = 465;
					break;
				default:
					port = 25;
					break;
			}

			bool isReal = false;
			try
			{
				IPHostEntry IPhst = Dns.GetHostEntry(hostname);
				IPEndPoint endPt = new IPEndPoint(IPhst.AddressList[0], port);
				Socket s = new Socket(endPt.AddressFamily,
									  SocketType.Stream, ProtocolType.Tcp);
				s.Connect(endPt);
				s.Close();
				return EmailValidationStatus.Valid;
			}
			catch (Exception ex)
			{
				return EmailValidationStatus.Unknown;
			}
		}
	}

